var express = require('express');
var router = express.Router();

// 加载formidable
let formidable = require("formidable");

// 加载时间戳包
let time = require('time-stamp');

// 加载path
let path = require('path');

// 加载fs
let fs = require('fs');
/* GET users listing. */
// router.get('/', function(req, res, next) {
//   res.send('respond with a resource');
// });
//加载mysql数据库
let mysql = require("mysql");
//配置mysql数据库
let config = {
  host: "localhost", 
  port: 3306, 
  user: "root", 
  password: "root", 
  database: "student", 
}

//连接数据库
let connection = mysql.createConnection(config);

//判断是否连接成功
connection.connect((err) => {
  if (err) {
    console.log("连接数据库失败")
  } else {
    console.log("数据库连接成功")
  }
})

router.get("/upload",(req,res)=>{
  res.render("upload.html")
})

//图片上传路由
router.post("/upload", (req, res) => {
  let form = new formidable.IncomingForm();
  //扩磁盘 把原来上传默认的虚拟地址指向到当前项目下
  form.uploadDir = __dirname + "/tmp";
  form.parse(req, (err, files, fildes) => {
    // console.log(fildes);
    let uploadfiles = fildes.pic1;
    // console.log(uploadfiles);
    //上传图片更名  随机数+时间戳
    let r = parseInt(Math.random() * 10000)
    //时间戳
    let t = time("YYYYMMDD");
    // 获取上传图片后缀名
    let extname = path.extname(uploadfiles.originalFilename)
    //console.log(extname);
    //规划上传图片地址
    //D:\Users\Desktop\0511\day9\代码/upload/638120220726.jpg
    let newpath = __dirname + "/upload/" + r + t + extname;
    let newimg = newpath.split("/upload")[1];
    console.log(newimg);
    //获取原来地址
    //c:
    let oldpath = uploadfiles.filepath;
    // console.log(newpath);
    //上传图片
    //方法是不能跨磁盘操作
    let sql = `insert into pic (image) value ("${newimg}")`;
    // console.log(sql);
    connection.query(sql, (err) => {
      if (err) {
        console.log("添加失败")
      } else {
        console.log("添加成功")
      }
    })
    fs.rename(oldpath, newpath, (err) => {
      if (err) {
        res.render("wait.html", {
          wait: 2,//等待时间
          content: "上传失败",
          href: "/users/upload"
      })
      } else {
        res.render("wait.html", {
          wait: 2,//等待时间
          content: "上传成功",
          href: "/users/index"
      })
      }
    })
  })
})
router.get("/index",(req,res)=>{
  //查询数据
  let sql = `select * from pic`;
  connection.query(sql, (err, doc) => {
      if (err) {
          console.log("查询失败")
      } else {
          //console.log(doc);
          res.render("index.html", { doc: doc });
          // console.log(doc);
      }
  })
})
// router.post("/index",(req,res)=>{
  
// })
module.exports = router;
